package com.etalk.crm.utils;

import okhttp3.*;

import java.io.IOException;

import static okhttp3.RequestBody.create;

/**
 * @author: Jordan
 * @date: 2019/1/9 23:49
 * @description:
 */
public class HttpUtils {


    private static final MediaType TYPE = MediaType.parse("application/json;charset=utf-8");
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * Get方法调用服务
     * @param url 请求地址
     * @return 结果
     */
    public static String httpGet(String url){
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            // 返回的是string 类型
            return response.body() != null ? response.body().string() : null;
        }catch (IOException ignored){

        }
            return null;
    }
    //Post方法调用服务

    /**
     * Post方法调用服务
     * @param url 请求地址
     * @param content 参数
     * @return 结果
     */
    public static String httpPost(String url,String content) throws IOException{
        try {
            RequestBody requestBody = RequestBody.create(TYPE,content);
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body() != null ? response.body().string() : null;
        }catch (IOException ignored){

        }
        return null;
    }

    /**
     * Post方法调用服务
     * @param url 请求地址
     * @param content 数据
     * @param authorization header授权
     * @return 结果
     */
    public static String httpPost(String url,String content,String authorization){
        try {
            RequestBody requestBody = RequestBody.create(TYPE,content);
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("authorization",authorization)
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            return response.body() != null ? response.body().string() : null;
        }catch (IOException ignored){

        }
        return null;
    }
}
